<template>
  <div>
    <el-breadcrumb class="margin-bottom-20 font-size-16" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!--搜索输入框-->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容..." clearable @clear="getUserList" v-model="queryInfo.query">
            <el-button slot="append" icon="el-icon-search"  @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--用户展示区域-->
      <el-row>
        <el-col :span="24">
          <!--用户表格-->
          <el-table class="margin-top-20" :data="userLIst" border>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="姓名" prop="username"></el-table-column>
            <el-table-column label="邮箱" prop="email"></el-table-column>
            <el-table-column label="电话" prop="mobile"></el-table-column>
            <el-table-column label="角色" prop="role_name"></el-table-column>
            <el-table-column label="状态">
              <template slot-scope="scope">
                <!--开关-->
                <el-switch v-model="scope.row.mg_state" @change="userRoleChange(scope.row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!--编辑-->
                <el-tooltip class="item" effect="dark" content="编辑用户" placement="top" :enterable="false">
                  <el-button @click="showEditorForm(scope.row)" type="primary" size="small" icon="el-icon-edit"></el-button>
                </el-tooltip>
                <!--删除-->
                <el-tooltip class="item" effect="dark" content="删除用户" placement="top" :enterable="false">
                  <el-button @click="deleteUser(scope.row)" type="danger" size="small" icon="el-icon-delete"></el-button>
                </el-tooltip>
                <!--分配权限-->
                <el-tooltip class="item" effect="dark" content="分配用户" placement="top" :enterable="false">
                  <el-button type="warning" size="small" icon="el-icon-setting" @click="setRole(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <!--分页-->
          <template>
            <div class="block">
              <el-pagination
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                      :current-page="queryInfo.pagenum"
                      :page-sizes="[1, 2, 5, 10]"
                      :page-size="queryInfo.pagesize"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="userTotal">
              </el-pagination>
            </div>
          </template>

        </el-col>
      </el-row>
    </el-card>
    <!--添加用户对话框-->
    <el-dialog
            title="添加用户"
            :visible.sync="dialogVisible"
            width="30%"
            :before-close="handleClose"
            @close="addUserFormClosed">


      <!--form-->
      <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item type="password" label="密码" prop="password">
          <el-input v-model="addUserForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!--footer-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUSer">确 定</el-button>
      </span>
    </el-dialog>

    <!--修改用户对话框-->
    <el-dialog
            title="添加用户"
            :visible.sync="dialogEditorVisible"
            width="30%"
            @closed="editorUserFormClosed">


      <!--form-->
      <el-form :model="editorUserForm" :rules="addUserFormRules" ref="editorUserFormRef" label-width="70px">
        <el-form-item label="id" prop="id" >
          <el-input v-model="editorUserForm.id" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editorUserForm.username" :disabled="true" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editorUserForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editorUserForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!--footer-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogEditorVisible = false">取 消</el-button>
        <el-button type="primary" @click="editorUSer">确 定</el-button>
      </span>
    </el-dialog>

    <!--分配用户对话框-->
    <el-dialog
            title="分配用户"
            :visible.sync="allocationRoleVisible"
            width="30%">


      <!--form-->
      <el-form :model="roleForm" :rules="addUserFormRules" ref="editorUserFormRef" label-width="70px">
        <!--<el-form-item label="手机" prop="mobile">
          <el-input v-model="editorUserForm.mobile" autocomplete="off"></el-input>
        </el-form-item>-->
        <p>用户名: {{roleForm.username}}</p>
        <p>用户名: {{roleForm.role_name}}</p>
        <template>
          <el-select v-model="roleId" placeholder="选择角色">
            <el-option
                    v-for="item in rolesList"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id">
            </el-option>
          </el-select>
        </template>
      </el-form>
      <!--footer-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="allocationRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="mdRole">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>



<script>


  export default {
    name: "User",
    components: {
    },
    data() {
      // 自定义邮箱验证
      var checkEmail = (rule, value, callback) => {
        // 邮箱正则
        const regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        // 判断
        if (regEmail.test(value)) return callback()
        else return callback(new Error("请输入正确的邮箱地址"))
      }
      // 自定义手机验证
      var checkPhone = (rule, value, callback) => {
        // 邮箱正则
        const regEmail = /^[1][3,4,5,7,8][0-9]{9}$/
        // 判断
        if (regEmail.test(value)) return callback()
        else return callback(new Error("请输入正确的手机号"))
      }
      return {
        queryInfo: {
          query : '',
          pagenum: 1,
          pagesize: 2,
        },
        userLIst: [],
        userTotal: 0,
        rolesList: [],
        roleForm: {},
        roleId: '',
        // 对话框开关
        dialogVisible: false,
        dialogEditorVisible: false,
        allocationRoleVisible: false,
        //User form
        addUserForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        editorUserForm: {

        },
        // UserForm 规则
        addUserFormRules: {
          username: [
            { required: true, message: '用户名不能为空',trigger: 'blur'},
            { min: 3, max: 10,  message: '用户名在3-10个字符',trigger: 'blur'}
          ],
          password: [
            { required: true, message: '密码不能为空',trigger: 'blur'},
            { min: 6, max: 15,  message: '密码在6-15个字符',trigger: 'blur'}
          ],
          email: [

            { required: true, message: '邮箱不能为空',trigger: 'blur'},
            {validator: checkEmail,trigger: 'blur'},
          ],
          phone: [
            { required: true, message: '手机不能为空',trigger: 'blur'},
            {validator: checkPhone ,trigger: 'blur'}
          ],
          mobile: [
            { required: true, message: '手机不能为空',trigger: 'blur'},
            {validator: checkPhone ,trigger: 'blur'}
          ]
        },

      }

    },
    methods: {
      getUserList() {
        this.$http.get("users",{params: this.queryInfo}).then(result => {

          // 判断
          if (result.data.meta.status !== 200) return this.$message.error("获取用户列表失败!");

          // 赋值
          this.userLIst = result.data.data.users
          this.userTotal = result.data.data.total
        })
      },
      getUserById(id) {
        this.$http.get('users/' + id).then(result => {
          if (result.data.meta.status !== 200) return this.$message.error("获取数据失败 -> user")
          this.editorUserForm = result.data.data
        })
      },
      // 当每页显示条数发生改变调用此函数
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize
        this.getUserList()
      },
      // 当前页发生改变调用此函数
      handleCurrentChange(newNum) {
        this.queryInfo.pagenum = newNum
        this.getUserList()
      },
      // 用改用户状态
      userRoleChange(user) {
        this.$http.put(`users/${user.id}/state/${user.mg_state}`).then(result => {
          // 修改失败
          if (result.data.meta.status !== 200) {
            user.mg_state = !user.mg_state
            return this.$message.error("修改用户状态失败!");
          }
          this.$message.success("修改用户状态成功!");

        })
      },
      // 对话框关闭
      handleClose(done) {
        this.$confirm('确认关闭？')
            .then(_ => {
              done();
            })
            .catch(_ => {});
      },
      // 对话框关闭事件
      addUserFormClosed() {
        this.$refs.addUserFormRef.resetFields();
      },
      editorUserFormClosed() {
        this.$refs.editorUserFormRef.resetFields();
      },
      //展示修改用户对话框
      showEditorForm(user) {
        this.dialogEditorVisible = true;
        this.getUserById(user.id);

      },
      // 表单提交预校验
      addUSer() {
        this.$refs.addUserFormRef.validate(valid => {
          if (!valid) return
            //发送请求
            this.$http.post('/users',this.addUserForm).then(result => {
              // 判断是否成功
              if (result.data.meta.status !== 201) return this.$message.error("添加用户失败!")
              this.getUserList()
              return this.$message.success("添加用户成功!")

            })
          // 关闭对话框
          this.dialogVisible = false
        })
      },
      editorUSer() {
        this.$refs.editorUserFormRef.validate(valid => {
          if (!valid) return
          //发送请求
          this.$http.put('users/' + this.editorUserForm.id,{email: this.editorUserForm.email,
            mobile: this.editorUserForm.mobile}).then(result => {
              if (result.data.meta.status !== 200) return this.$message.error("修改用户失败 状态码: " + result.meta.status)
              this.$message.success("修改用户成功")
              // 关闭对话框
              this.dialogEditorVisible = false
              this.getUserList()

          })
        })
      },
      deleteUser(user) {
        this.$confirm('此操作将永久删除该用户, 是否继续?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          this.$http.delete('users/' + user.id).then(result => {
            if (result.data.meta.status !== 200) this.$message.error("删除失败")
            this.getUserList()
            this.$message.success("删除成功")
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 分配用户
      setRole(role) {
        this.roleForm = role
        // 获取角色
        this.$http.get('/roles').then(result => {
          this.rolesList = result.data.data

        })
        this.allocationRoleVisible = true
      },
      mdRole() {
        if (!this.roleId) return this.$message.error("错误!")
        this.$http.put(`users/${this.roleForm.id}/role`,{rid: this.roleId}).then(result => {
          if (result.data.meta.status !== 200) return this.$message.error("修改失败!")
          this.allocationRoleVisible = false
          return this.$message.success("修改成功!")

        })
      }
    },
    created() {
      this.getUserList();
    }
  }
</script>

<style scoped>

</style>